package com.dycong.common.network;

import lombok.extern.log4j.Log4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

/**
 * Created by Yu on 2015/1/29.
 */
@Log4j
public class SimpleHttpClient extends AbstractHttpClient {


    @Override
    public String doPost(String url, String encoding) throws IOException {
        return doPost(url, encoding, null, null);
    }

    @Override
    public String doGet(String url, String encoding) throws IOException {
        return doGet(url, encoding, null, null);
    }

    @Override
    public String postJson(String url, String encoding, String json) throws IOException {
        return postJson(url, encoding, null, json);
    }

    @Override
    public String doPost(String url, String encoding, Map<String, String> headerMap, Map<String, String> parameters) throws IOException {
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        return executeRequestByDefault(client, post, encoding, headerMap, parameters);
    }

    @Override
    public String doGet(String url, String encoding, Map<String, String> headerMap) throws IOException {
        HttpClient client = getHttpClient();
        HttpGet get = new HttpGet(url);
        get.setHeader("User-Agent", super.userAgent);

        //set proxy
        proxyConfig.ifPresent(get::setConfig);
        HttpResponse httpResponse = client.execute(get);
        try {
            return EntityUtils.toString(httpResponse.getEntity(), encoding);
        } finally {
            HttpClientUtils.closeQuietly(httpResponse);
        }
    }

    @Override
    protected HttpClient getHttpClient() {
        return HttpClients.createDefault();
    }

}
